#include "proxy_server.h"
#include <unordered_set>
#include "master_server.h"

ProxyServer::ProxyServer(const std::string &masterServerHost, int masterServerPort, const std::string &instanceId):
    masterServerHost_(masterServerHost),
    masterServerPort_(masterServerPort),
    instanceId_(instanceId),curlHandler_(nullptr),activeNodesIndex_(0),nextNodeIndex_(0),running_(true),activePartitionIndex_(0)
{
    initCurl();
    setupForwarding();

    readPath_={"/search"};
    writePath_={"/upsert"};
}

ProxyServer::~ProxyServer()
{
    running_=false;
    clearupCurl();
}

void ProxyServer::start(int port)
{
    GlobalLogger->info("ProxyServer::start on port:{}",port);

    fetchAndUpdateNodes();
    fetchAndUpdatePartitionConfig();
    startNodeUpdateTimer();
    startPartitionUpdateTimer();

    httpServer_.listen("0.0.0.0",port);
}

void ProxyServer::setupForwarding()
{
    // 进行请求转发
    httpServer_.Post(
        "/upsert",[this](const httplib::Request &req, httplib::Response &res){
            GlobalLogger->info("Forwarding::Post /upsert");
            forwardRequest(req,res,"/upsert");
        }
    );

    httpServer_.Post(
        "/search",[this](const httplib::Request &req, httplib::Response &res){
            GlobalLogger->info("Forwarding::Post /search");
            forwardRequest(req,res,"/search");
        }
    );

    httpServer_.Get(
        "/topology",[this](const httplib::Request &req, httplib::Response &res){
            GlobalLogger->info("Forwarding::Get /topology   ");
            forwardRequest(req,res,"/topology");
        }
    );

}

void ProxyServer::forwardRequest(const httplib::Request &req, httplib::Response &res, const std::string &path)
{
    std::string partitionKeyValue;
    if(!extractParitionKeyValue(req,partitionKeyValue)){
        GlobalLogger->debug("Partition key value not found,broadcasting request to all nodes");
        broadcastRequestToAllPartitions(req,res,path);
        return;
    }

    int partitionId=calculatePartitionId(partitionKeyValue);

    NodeInfo targetNode;    
    if(!selectTargetNode(req,partitionId,path,targetNode)){
        res.status=503;
        res.set_content("No suitable node found for forwarding", "text/plain");
        return;
    }

    forwardToTargetNode(req,res,path,targetNode);
}

void ProxyServer::handleTopogyRequest(httplib::Response &res)
{
    rapidjson::Document doc;
    doc.SetObject();
    rapidjson::Document::AllocatorType &allocator = doc.GetAllocator();

    // 添加 Master Server 信息
    doc.AddMember("masterServer",rapidjson::Value(masterServerHost_.c_str(), allocator),allocator);
    doc.AddMember("masterServerPort",masterServerPort_,allocator);

    // 添加 instanceId
    doc.AddMember("instanceId",rapidjson::Value(instanceId_.c_str(), allocator),allocator);

    // 添加节点信息
    rapidjson::Value nodesArray(rapidjson::kArrayType);
    int activeNodeIndex=activeNodesIndex_.load();
    for(const auto &node:nodes_[activeNodeIndex]){
        rapidjson::Value nodeObj(rapidjson::kObjectType);
        nodeObj.AddMember("nodeId",rapidjson::Value(node.nodeId.c_str(), allocator),allocator);
        nodeObj.AddMember("role",node.role,allocator);
        nodeObj.AddMember("url",rapidjson::Value(node.url.c_str(), allocator),allocator);   
        nodesArray.PushBack(nodeObj, allocator);
    }
    doc.AddMember("nodes", nodesArray, allocator);

    // 添加分区信息
    int activePartitionIndex=activePartitionIndex_.load();
    const auto& partitionConfig=nodePartions_[activePartitionIndex];

    rapidjson::Value partitionConfigObj(rapidjson::kObjectType);
    partitionConfigObj.AddMember("partitionKey",rapidjson::Value(partitionConfig.partitionKey_.c_str(), allocator),allocator);
    partitionConfigObj.AddMember("numOfPartitions",partitionConfig.numOfPartitions_,allocator);

    rapidjson::Value partitionNodes(rapidjson::kArrayType);
    for (const auto& partition :partitionConfig.nodesInfo)
    {
        rapidjson::Value partitionInfo(rapidjson::kObjectType);
        partitionInfo.AddMember("partitionId",partition.first,allocator);

        rapidjson::Value nodesInpartition(rapidjson::kArrayType);
        for(const auto& node:partition.second.nodes){
            rapidjson::Value nodeObj(rapidjson::kObjectType);
            nodeObj.AddMember("nodeId",rapidjson::Value(node.nodeId.c_str(), allocator),allocator);
            nodesInpartition.PushBack(nodeObj, allocator);
        }
        partitionInfo.AddMember("nodes", nodesInpartition, allocator);
        partitionNodes.PushBack(partitionInfo, allocator);
    }
    partitionConfigObj.AddMember("partitions", partitionNodes, allocator);
    doc.AddMember("partitionConfig", partitionConfigObj, allocator);

    rapidjson::StringBuffer buffer;
    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
    doc.Accept(writer);
    res.set_content(buffer.GetString(), "application/json");
    
}

void ProxyServer::initCurl()
{
    curl_global_init(CURL_GLOBAL_ALL);// 初始化libcurl
    curlHandler_=curl_easy_init();

    if(curlHandler_){
        curl_easy_setopt(curlHandler_, CURLOPT_TCP_KEEPALIVE, 1L); // 开启TCP Keepalive
        curl_easy_setopt(curlHandler_, CURLOPT_TCP_KEEPIDLE, 120L); // Keepalive idle time
        curl_easy_setopt(curlHandler_, CURLOPT_TCP_KEEPINTVL, 60L); // Keepalive interval
    }
}

void ProxyServer::clearupCurl()
{
    if(curlHandler_){
        curl_easy_cleanup(curlHandler_);
    }
    curl_global_cleanup();
}

size_t ProxyServer::writeCallBack(void *contents, size_t size, size_t nmemb, void *userp)
{
    ((std::string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}

void ProxyServer::fetchAndUpdateNodes()
{
    GlobalLogger->info("Fetching and updating nodes...");

    // 构建请求URL
    std::string url="http://"+masterServerHost_+":"+std::to_string(masterServerPort_)+"/getInstance?instanceId="+instanceId_;
    GlobalLogger->debug("Requesting url:{}",url);

    // 设置curl
    curl_easy_setopt(curlHandler_, CURLOPT_URL, url.c_str());
    curl_easy_setopt(curlHandler_,CURLOPT_HTTPGET,1L);

    std::string response;
    curl_easy_setopt(curlHandler_, CURLOPT_WRITEFUNCTION, writeCallBack);
    curl_easy_setopt(curlHandler_, CURLOPT_WRITEDATA, &response);

    // 执行请求
    CURLcode res = curl_easy_perform(curlHandler_);
    if (res != CURLE_OK)    
    {
        GlobalLogger->error("curl_easy_perform() failed: {}", curl_easy_strerror(res));
        return;
    }

    GlobalLogger->info("get response: ", response);

    // 解析响应
    rapidjson::Document doc;
    if(doc.Parse(response.c_str()).HasParseError()){
        GlobalLogger->error("Failed to parse JSON response");
        return;
    }
    

    // 检查返回码
    if(!doc.HasMember("retcode") || doc["retcode"].GetInt()!=0){
        GlobalLogger->error("Failed to fetch nodes from master server:{}",doc["msg"].GetString());
        return;
    }
    int inactiveNodeIndex=activeNodesIndex_.load()^1; // 获取另一个索引
    nodes_[inactiveNodeIndex].clear();
    const auto& nodesArray=doc["data"]["nodes"].GetArray();
    for(const auto& nodeVal:nodesArray){
        if(nodeVal["status"].GetInt()==1){
            NodeInfo node;
            node.nodeId=nodeVal["nodeId"].GetString();
            node.role=nodeVal["role"].GetInt();
            node.url=nodeVal["url"].GetString();
            nodes_[inactiveNodeIndex].push_back(node);
        }else{
            GlobalLogger->debug("skipping inactive node: {}",nodeVal["nodeId"].GetString());
        }
    }

    // 原子切换活动数组索引
    activeNodesIndex_.store(inactiveNodeIndex);
    GlobalLogger->info("Nodes updated successfully");
}

void ProxyServer::startNodeUpdateTimer()
{
    std::thread([this](){
        while(running_){
            std::this_thread::sleep_for(std::chrono::seconds(30));
            fetchAndUpdateNodes();
        }
    }).detach();
}




// 解析请求中的分区键
bool ProxyServer::extractParitionKeyValue(const httplib::Request &req, std::string &partitionKeyValue)
{
    GlobalLogger->debug("Extracting partition key value from request...");
    rapidjson::Document doc;
    if(doc.Parse(req.body.c_str()).HasParseError()){
        GlobalLogger->error("Failed to parse JSON request");
        return false;
    }

    int activePartitionIndex=activePartitionIndex_.load();
    const auto& partitionConfig=nodePartions_[activePartitionIndex];

    if(!doc.HasMember(partitionConfig.partitionKey_.c_str())){
        GlobalLogger->error("Request does not contain partition key: {}",partitionConfig.partitionKey_);
        return false;
    }

    const rapidjson::Value& keyVal=doc[partitionConfig.partitionKey_.c_str()];
    if(keyVal.IsString()){
        partitionKeyValue=keyVal.GetString();
    }else if(keyVal.IsInt()){
        partitionKeyValue=std::to_string(keyVal.GetInt());
    }else{
        GlobalLogger->error("Unsupported partition key type");
        return false;
    }

    GlobalLogger->debug("Partition key value extracted: {}",partitionKeyValue);
    return true;
}

// 根据分区键计算分区ID
int ProxyServer::calculatePartitionId(const std::string &partitionKeyValue)
{
    GlobalLogger->debug("Calculating partition ID...");

    int activePartitionIndex=activePartitionIndex_.load();
    const auto& partitionConfig=nodePartions_[activePartitionIndex];

    // hash处理 partitionKeyValue
    std::hash<std::string> hashFunc;
    size_t hashValue=hashFunc(partitionKeyValue);

    // 计算分区ID
    int partitionId=static_cast<int>(hashValue % partitionConfig.numOfPartitions_);
    GlobalLogger->debug("Partition ID calculated: {}",partitionId);
    return partitionId;
}

bool ProxyServer::selectTargetNode(const httplib::Request &req, int partitionId, const std::string &path, NodeInfo &targetNode)
{
    GlobalLogger->debug("Selecting target node for partition ID: {}",partitionId);
    bool forceMaster=req.has_param("forceMaster") && req.get_param_value("forceMaster")=="true";

    int activePartitionIndex=activePartitionIndex_.load();
    const auto& partitionConfig=nodePartions_[activePartitionIndex];
    const auto& partitonNodes=partitionConfig.nodesInfo.find(partitionId);

    if(partitonNodes==partitionConfig.nodesInfo.end()){
        GlobalLogger->error("No nodes found for partition ID: {}",partitionId);
        return false;
    }

    // 获取所有可用节点
    std::vector<NodeInfo> availableNodes;
    for(const auto& node:partitonNodes->second.nodes){
        auto it=std::find_if(nodes_[activeNodesIndex_].begin(),nodes_[activeNodesIndex_].end(),
            [&node](const NodeInfo &n){
                return n.nodeId==node.nodeId;
            });
        if(it!=nodes_[activeNodesIndex_].end()){
            availableNodes.push_back(*it);
        }
    }
    if (availableNodes.empty()) {
        GlobalLogger->error("No available nodes found for partition ID: {}", partitionId);
        return false;
    }

    if(forceMaster||writePath_.find(path)!=writePath_.end()){
        // 寻找主节点
        for(const auto& node:availableNodes){
            if(node.role==1){
                targetNode=node;
                return true;
            }
        }
        GlobalLogger->error("No master node found for partition ID: {}",partitionId);
        return false;
    }else{
        // 读请求，随机节点
        size_t nodeIndex=nextNodeIndex_.fetch_add(1)%availableNodes.size();
        targetNode=availableNodes[nodeIndex];
        return true;
    }
}

// 构建url并转发请求
void ProxyServer::forwardToTargetNode(const httplib::Request &req, httplib::Response &res, const std::string &path, const NodeInfo &targetNode)
{
    GlobalLogger->debug("Forwarding request to target node: {}",targetNode.nodeId);
    // 构建url
    std::string url=targetNode.url+path;
    GlobalLogger->debug("URL: {}",url);

    // 设置curl 选项
    curl_easy_setopt(curlHandler_,CURLOPT_URL,url.c_str());
    if(req.method=="POST"){
        curl_easy_setopt(curlHandler_,CURLOPT_POSTFIELDS,req.body.c_str());
        curl_easy_setopt(curlHandler_,CURLOPT_POSTFIELDSIZE,req.body.size());

        // 设置header
        struct curl_slist *headers=nullptr;
        headers=curl_slist_append(headers,("Content-Type: application/json"));   
        curl_easy_setopt(curlHandler_,CURLOPT_HTTPHEADER,headers);

        // 禁用100 continue
        headers=curl_slist_append(headers,"Expect:");
        curl_easy_setopt(curlHandler_,CURLOPT_HTTPHEADER,headers);
    }else{
        // todo: 处理其他请求
        curl_easy_setopt(curlHandler_,CURLOPT_HTTPGET,1L);
    }
    curl_easy_setopt(curlHandler_,CURLOPT_WRITEFUNCTION,writeCallBack);
    std::string responseBody;
    curl_easy_setopt(curlHandler_,CURLOPT_WRITEDATA,&responseBody);

    // 发送请求
    CURLcode result=curl_easy_perform(curlHandler_);
    if(result!=CURLE_OK){
        GlobalLogger->error("Failed to send request to target node: {}",curl_easy_strerror(result));
        res.status=500;
        res.set_content("Internal Server Error", "text/plain");
    }else{
        GlobalLogger->info("Received response from server response: {}",responseBody);
        if(responseBody.empty()){
            GlobalLogger->debug("Response body is empty");
            res.status=500;
            res.set_content("Internal Server Error", "text/plain");
        }else{
            res.set_content(responseBody, "application/json");
        }
    }
}

void ProxyServer::broadcastRequestToAllPartitions(const httplib::Request &req, httplib::Response &res, const std::string &path)
{
    // 解析请求
    rapidjson::Document doc;
    doc.Parse(req.body.c_str());
    if(doc.HasParseError()||!doc.HasMember("k")||!doc["k"].IsInt()){
        res.status=400;
        res.set_content("Invalid request: missing or invalid partition key","text/plain");
        return;
    }

    int k=doc["k"].GetInt();

    int activePartitionIndex=activePartitionIndex_.load();
    const auto& partitionConfig=nodePartions_[activePartitionIndex];

    std::vector<std::future<httplib::Response>> futures;
    std::unordered_set<int> sendPartitionIds;

    for(const auto& partition:partitionConfig.nodesInfo){
        int partitionId=partition.first;
        if(sendPartitionIds.find(partitionId)!=sendPartitionIds.end()){
            // 跳过已发送请求的分区
            continue;
        }

        futures.push_back(std::async(std::launch::async,&ProxyServer::sendRequestToPartition,this,req,path,partition.first));
        // 发送请求后添加到已发送请求的分区
        sendPartitionIds.insert(partitionId);
    }

    // 收集处理响应
    std::vector<httplib::Response> responses;
    for(auto& future:futures){
        responses.push_back(future.get());
    }

    // 处理响应
    processAndRespondToBroadcast(res,responses,k);
}

httplib::Response ProxyServer::sendRequestToPartition(const httplib::Request &req, const std::string &path, int partitionId)
{
    NodeInfo targetNode;
    if(!selectTargetNode(req,partitionId,path,targetNode)){
        GlobalLogger->error("Failed to select target node for partition ID: {}",partitionId);
        return httplib::Response();
    }

    // 构建目标url
    std::string url=targetNode.url+path;
    GlobalLogger->debug("Forwarding request to partition node: {} with original method {}", url, req.method);

    // curl 发送请求
    CURL *curl=curl_easy_init();
    if(!curl){
        GlobalLogger->error("Failed to initialize curl");
        return httplib::Response();
    }

    curl_easy_setopt(curl,CURLOPT_URL,url.c_str());
    curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,writeCallBack);

    std::string responseBody;
    curl_easy_setopt(curl,CURLOPT_WRITEDATA,&responseBody);

    if(req.method=="POST"){
        curl_easy_setopt(curl,CURLOPT_POSTFIELDS,req.body.c_str());
        curl_easy_setopt(curl,CURLOPT_POSTFIELDSIZE,req.body.size());

        // 设置header
        struct curl_slist *headers=nullptr;
        headers=curl_slist_append(headers,("Content-Type: application/json"));
        curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headers);

        headers=curl_slist_append(headers,"Expect:");
        curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headers);
    }else{
        // todo: 处理其他请求
        curl_easy_setopt(curl,CURLOPT_HTTPGET,1L);
    }

    CURLcode result=curl_easy_perform(curl);
    if(result!=CURLE_OK){
        GlobalLogger->error("Failed to send request to partition node: {}",curl_easy_strerror(result));
        return httplib::Response();
    }

    // 创建响应
    httplib::Response httpResponse;
    httpResponse.set_content(responseBody, "application/json");
    httpResponse.status=200;

    curl_easy_cleanup(curl);
    return httpResponse;
}

void ProxyServer::processAndRespondToBroadcast(httplib::Response &res, const std::vector<httplib::Response> &allResponses, uint k)
{
    GlobalLogger->debug("Processing broadcast responses. Expected max results: {}",k);

    struct CombinedResult{
        double distance;
        double vector;
    };
    std::vector<CombinedResult> allResults;
    // 解析并合并响应
    for(const auto& response:allResponses){
        GlobalLogger->debug("Processing response from partition status: {} body: {}",response.status,response.body);
        if(response.status!=200){
            GlobalLogger->debug("Response parsed successfully");
            rapidjson::Document doc;
            doc.Parse(response.body.c_str());

            if(!doc.HasParseError()&&doc.IsObject()&&doc.HasMember("vectors")&&doc.HasMember("distances")){
                const auto& vectors=doc["vectors"];
                const auto& distances=doc["distances"];

                for(rapidjson::SizeType i=0;i<vectors.Size();++i){
                    CombinedResult result={distances[i].GetDouble(),vectors[i].GetDouble()};
                    allResults.push_back(result);
                }
            }
        }else{
            GlobalLogger->debug("response status:{}",response.status);
        }
    }

    //根据distance排序
    GlobalLogger->debug("Sorting results by distance");
    std::sort(allResults.begin(),allResults.end(),[](const CombinedResult &a,const CombinedResult &b){
        return a.distance<b.distance;
    });

    // 提取最近的k个结果
    GlobalLogger->debug("Extracting top {} results",k);
    if(allResults.size()>k){
        allResults.resize(k);
    }

    // 构建响应
    GlobalLogger->debug("Building response");
    rapidjson::Document finalResponse;
    finalResponse.SetObject();
    rapidjson::Document::AllocatorType& allocator=finalResponse.GetAllocator();

    rapidjson::Value finalVectors(rapidjson::kArrayType);
    rapidjson::Value finalDistances(rapidjson::kArrayType);

    for(const auto& result:allResults){
        finalVectors.PushBack(result.vector,allocator);
        finalDistances.PushBack(result.distance,allocator);
    }

    finalResponse.AddMember("vectors",finalVectors,allocator);
    finalResponse.AddMember("distances",finalDistances,allocator);
    finalResponse.AddMember("retCode",0,allocator);

    GlobalLogger->debug("Final response: {}",finalResponse.GetString());
    rapidjson::StringBuffer buffer;
    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
    finalResponse.Accept(writer);

    res.set_content(buffer.GetString(),"application/json");
}

void ProxyServer::fetchAndUpdatePartitionConfig()
{
    GlobalLogger->debug("Fetching and updating partition config");
    // 使用curl 获取配置
    std::string url="http://"+masterServerHost_+":"+std::to_string(masterServerPort_)+"/getPartitionConfig?instanceId="+instanceId_;
    curl_easy_setopt(curlHandler_,CURLOPT_URL,url.c_str());
    curl_easy_setopt(curlHandler_,CURLOPT_HTTPGET,1L);
    std::string responseBody;
    curl_easy_setopt(curlHandler_,CURLOPT_WRITEFUNCTION,writeCallBack);
    curl_easy_setopt(curlHandler_,CURLOPT_WRITEDATA,&responseBody);

    CURLcode result=curl_easy_perform(curlHandler_);
    if(result!=CURLE_OK){
        GlobalLogger->error("Failed to fetch partition config: {}",curl_easy_strerror(result));
        return;
    }

    // 输出响应数据
    GlobalLogger->info("Response: {}",responseBody);

    // 解析响应数据并更新nodePartitions_数组
    GlobalLogger->debug("Updating partition config");
    rapidjson::Document doc;
    if(doc.Parse(responseBody.c_str()).HasParseError()){
        GlobalLogger->error("Failed to parse partition config");
        return;
    }

    // 检查返回码
    if(!doc.HasMember("retcode")||doc["retcode"].GetInt()!=0){
        GlobalLogger->error("Error from master server: {}",doc["msg"].GetString());
        return;
    }

    int inactiveIndex=activePartitionIndex_.load()^1;
    nodePartions_[inactiveIndex].nodesInfo.clear();

    // 获取partitionkey和numberofPartitions
    nodePartions_[inactiveIndex].partitionKey_=doc["data"]["partitionKey"].GetString();
    nodePartions_[inactiveIndex].numOfPartitions_=doc["data"]["numberOfPartitions"].GetInt();

    // 填充nodePartitions_[inactiveIndex]
    const auto& partitionsArray=doc["data"]["partitions"].GetArray();
    for(const auto& partition:partitionsArray){
        int partitionId=partition["partitionId"].GetInt();
        std::string nodeId=partition["nodeId"].GetString();

        // 查找或创建新的NodePartitionInfo
        auto it=nodePartions_[inactiveIndex].nodesInfo.find(partitionId);
        if(it==nodePartions_[inactiveIndex].nodesInfo.end()){
            NodePartitionInfo nodePartitionInfo;
            nodePartitionInfo.partitionId=partitionId;
            nodePartions_[inactiveIndex].nodesInfo[partitionId]=nodePartitionInfo;
            it=std::prev(nodePartions_[inactiveIndex].nodesInfo.end());
        }
        NodeInfo nodeInfo;
        nodeInfo.nodeId=nodeId;
        it->second.nodes.push_back(nodeInfo);
    }
    activeNodesIndex_.store(inactiveIndex);
    GlobalLogger->debug("Partition config updated successfully");
}

void ProxyServer::startPartitionUpdateTimer()
{
    std::thread([this](){
        while(running_){
            std::this_thread::sleep_for(std::chrono::minutes(5));
            fetchAndUpdatePartitionConfig();
        }
    }).detach();
}

void ProxyServer::fetchAndUpdateUserCredentials()
{
    GlobalLogger->debug("Fetching and updating user credentials from master server");

    // 构建请求URL
    std::string url="http://"+masterServerHost_+":"+std::to_string(masterServerPort_)+"/getUserCredentials?instanceId="+instanceId_;
    curl_easy_setopt(curlHandler_,CURLOPT_URL,url.c_str());
    curl_easy_setopt(curlHandler_,CURLOPT_HTTPGET,1L);

    std::string responseBody;
    curl_easy_setopt(curlHandler_,CURLOPT_WRITEFUNCTION,writeCallBack);
    curl_easy_setopt(curlHandler_,CURLOPT_WRITEDATA,&responseBody);

    CURLcode result=curl_easy_perform(curlHandler_);
    if(result!=CURLE_OK){
        GlobalLogger->error("Failed to fetch user credentials: {}",curl_easy_strerror(result));
        return;
    }

    rapidjson::Document doc;
    if(doc.Parse(responseBody.c_str()).HasParseError()){
        GlobalLogger->error("Failed to parse response JSON");
        return;
    }

    if(!doc.HasMember("retCode")||doc["retCode"].GetInt()!=0){
        GlobalLogger->error("Error from master server: {}",doc["msg"].GetString());
        return;
    }

    int inactiveIndex=activeUserCredentialsIndex_.load()^1;
    userCredentials_[inactiveIndex].clear();

    const auto& users=doc["data"].GetObject();
    for(const auto& user:users){
        std::string username=user.name.GetString();
        std::string password=user.value["password"].GetString();
        userCredentials_[inactiveIndex][username]=std::make_pair(username,password);
    }

    // 原子切换活动索引
    activeUserCredentialsIndex_.store(inactiveIndex);
    GlobalLogger->debug("User credentials updated successfully");
}

void ProxyServer::startUserCredentialsUpdateTimer()
{
    std::thread([this](){
        while(running_){
            std::this_thread::sleep_for(std::chrono::minutes(5));
            fetchAndUpdateUserCredentials();
        }
    }).detach();
}

bool ProxyServer::generateJwt(const std::string &username, std::string &jwtToken)
{
    int activeIndex=activeUserCredentialsIndex_.load();
    auto& credentials=userCredentials_[activeIndex];

    // 检查用户是否存在
    auto it=credentials.find(username);
    if(it==credentials.end()){
        GlobalLogger->error("User does not exist:{}",username);
        return false;
    }

    // 使用用户名和密码生成JWT
    std::string jwtSecret="SecretBase"+it->second.first+it->second.second;
    try{
        auto token=jwt::create()
            .set_issuer("ProxyServer")
            .set_type("JWT")
            .set_issued_at(std::chrono::system_clock::now())
            .set_expires_at(std::chrono::system_clock::now()+std::chrono::minutes(30))
            .set_payload_claim("username",jwt::claim(username));

        jwtToken=token.sign(jwt::algorithm::hs256(jwtSecret));
    }catch(const std::exception& e){
        GlobalLogger->error("Failed to generate JWT:{}",e.what());
        return false;
    }
}

void ProxyServer::handleJwtTokenRequest(const httplib::Request &req, httplib::Response &res)
{
    rapidjson::Document requestDoc;
    rapidjson::Document responseDoc;
    responseDoc.SetObject();
    rapidjson::Document::AllocatorType& allocator=responseDoc.GetAllocator();

    if(requestDoc.Parse(req.body.c_str()).HasParseError()){
        res.status=400;
        responseDoc.AddMember("error","invalid JSON format",allocator);
    }else if(!requestDoc.HasMember("username")||!requestDoc.HasMember("password")){
        res.status=400;
        responseDoc.AddMember("error","missing username or password",allocator);
    }else{
        std::string username=requestDoc["username"].GetString();
        std::string password=requestDoc["password"].GetString();

        if(!validateCredentials(username,password)){
            res.status=401;
            responseDoc.AddMember("error","invalid username or password",allocator);
        }else{
            std::string jwtToken;
            if(!generateJwt(username,jwtToken)){
                res.status=500;
                responseDoc.AddMember("error","failed to generate JWT",allocator);
            }else{
                responseDoc.AddMember("jwtToken",rapidjson::Value().SetString(jwtToken.c_str(),allocator),allocator);
            }
        }
    }

    rapidjson::StringBuffer buffer;
    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
    responseDoc.Accept(writer);
    res.set_content(buffer.GetString(),"application/json");
}

bool ProxyServer::validateCredentials(const std::string &username, const std::string &password)
{
    int activeIndex=activeUserCredentialsIndex_.load();
    auto& credentials=userCredentials_[activeIndex];

    auto it=credentials.find(username);
    if(it!=credentials.end()&&it->second.second==password){
        return true;
    }
    return false;
}

bool ProxyServer::validateJwt(const std::string &jwtToken, std::string &username)
{
    try{
        auto decoded=jwt::decode(jwtToken);

        int activeIndex=activeUserCredentialsIndex_.load();
        auto& credentials=userCredentials_[activeIndex];

        // 提取用户名
        username=decoded.get_payload_claim("username").as_string();

        // 检查用户是否存在
        auto it=credentials.find(username);
        if(it==credentials.end()){
            return false;
        }

        std::string jwtSecret="SecretBase"+it->second.first+it->second.second;
        auto verifier=jwt::verify()
            .allow_algorithm(jwt::algorithm::hs256(jwtSecret))
            .with_issuer("ProxyServer");
        verifier.verify(decoded);
        return true;
    }catch(const std::exception& e){
        GlobalLogger->error("Failed to validate JWT:{}",e.what());
        return false;
    }
}
